
/**
 * Module dependencies.
 */
logger = require('./util/logger');// 不加var表示全局定义
settings = require('./settings');
var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
//  , params = require('express-params')
//  ,flash = require('connect-flash')
  , partials = require('express-partials');
var app = express();

var RedisStore = require('connect-redis')(express);
var client = require('./util/redis');
var job = require('./util/cron');

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());// 用于支持定制的HTTP方法（如put、delete等HTTP方法）
  app.use(express.cookieParser(settings.cookieSecret));//your secret here 加密字符串
//  app.use(express.session());
//  app.use(flash());
  app.use(express.session({ secret:settings.sessionSecret, store: new RedisStore }));
  app.use(cacheSession);
  app.use(defaultFlash);
//  params.extend(app);
  app.use(partials()); //这个一定要写在app.use(app.router)之前
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

routes(app);

// 额外记录下sessionID，方便统计在线人数。TODO 需要加上redis过期时间
function cacheSession(req, res, next){
    var field = req.sessionID;
    client.hexists(settings.sessionKey,field, function (err, re) {
        if(!err&&re>0){
//              logger.info("存在");
        }else{
            client.hset(settings.sessionKey,field, Date.now());
        }
        next();
    });
}

// 设置页面要用的公共值
function defaultFlash(req, res, next) {
    if(!res.locals.project)res.locals.project = settings.project;
    if(!res.locals.title)res.locals.title = settings.title;
    if(!res.locals.error)res.locals.error = '';
    if(!res.locals.success)res.locals.success = '';
    if(!res.locals.user)res.locals.user = req.session ? req.session.user : null;
    next();
};

// 启动服务器
http.createServer(app).listen(app.get('port'), function(){
    // 启动定时任务
    job.start();
    logger.info("Express server listening on port " + app.get('port'));
});
